package com.yxch.admin.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


//同样还是交给IOC容器管理吧
@Component
public class AliOSSUtils {

    @Autowired
    AliOSSproperties aliOSSproperties;

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        String endpoint = aliOSSproperties.getEndpoint();
        String accessKeyId = aliOSSproperties.getAccessKeyId();
        String accessKeySecret = aliOSSproperties.getAccessKeySecret();
        String bucketName = aliOSSproperties.getBucketName();
        String URL = null;
        //上传文件的输入流
        InputStream inputStream = file.getInputStream();

        //文件重命名使用UUID
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));


        //上传OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } finally {
            ossClient.shutdown();
        }
        //文件访问路径
        //总之就是进行一些奇怪的拼接
        String[] splits = endpoint.split("//");
        URL = splits[0] + "//" + bucketName + "." + splits[1] + "/" + fileName;
        return URL;
    }
}
